# -*- coding: utf-8 -*-
import math
import pyproj
import tkinter as tk
from threading import Thread

def lonlat2utm(lon,lat):
    z=int(lon/6+31)
    proj = pyproj.Proj(proj='utm',zone=z,ellps='WGS84')
    return proj(lon, lat),z

def utm2lonlat(x,y,z):
    proj = pyproj.Proj(proj='utm',zone=z,ellps='WGS84')
    return proj(x, y,inverse=True)

def insec(p1,r1,p2,r2):
    x = p1[0]
    y = p1[1]
    R = r1
    a = p2[0]
    b = p2[1]
    S = r2
    d = math.sqrt((abs(a-x))**2 + (abs(b-y))**2)
    if d > (R+S) or d < (abs(R-S)):
#        print ("没有公共点")
        return 
    elif d == 0 and R==S :
#        print ("两个圆同心")
        return 
    else:
        A = (R**2 - S**2 + d**2) / (2 * d)
        h = math.sqrt(R**2 - A**2)
        x2 = x + A * (a-x)/d
        y2 = y + A * (b-y)/d
        x3 = x2 - h * (b - y) / d
        y3 = y2 + h * (a - x) / d
        x4 = x2 + h * (b - y) / d
        y4 = y2 - h * (a - x) / d
        c1=[x3, y3]
        c2=[x4, y4]
        return c1,c2

def location_trans(p1,r1,p2,r2):
    z1=lonlat2utm(p1[0],p1[1])
    z2=lonlat2utm(p2[0],p2[1])
    z=int((z1[1]+z2[1])/2)    
    C=insec(z1[0],r1,z2[0],r2)
    if C:
        a=utm2lonlat(C[0][0],C[0][1],z)
        b=utm2lonlat(C[1][0],C[1][1],z)
        return a,b
    else:
        return None,None

def location_min(p1,p2,p,r):
    d1=math.fabs(r-math.sqrt((p[0]-p1[0])**2+(p[1]-p1[1])**2))
    d2=math.fabs(r-math.sqrt((p[0]-p2[0])**2+(p[1]-p2[1])**2))
    if d1<d2:
        return p1
    else:
        return p2
    
def location_judg(p1,r1,p2,r2,p3,r3):
    li=[]
    
    z1=lonlat2utm(p1[0],p1[1])
    z2=lonlat2utm(p2[0],p2[1])
    z3=lonlat2utm(p3[0],p3[1])
    
    z12=int((z1[1]+z2[1])/2)
    z13=int((z1[1]+z3[1])/2)
    z23=int((z2[1]+z3[1])/2)
    z=int((z12+z13+z23)/3)
    
    C12=insec(z1[0],r1,z2[0],r2)
    C13=insec(z1[0],r1,z3[0],r3)
    C23=insec(z2[0],r2,z3[0],r3)
    
    if C12:
        m12=location_min(C12[0],C12[1],z3[0],r3)
        li.append(utm2lonlat(m12[0],m12[1],z12))
    else:
        li.append(None)
    if C13:
        m13=location_min(C13[0],C13[1],z2[0],r2)
        li.append(utm2lonlat(m13[0],m13[1],z13))
    else:
        li.append(None)
    if C23:
        m23=location_min(C23[0],C23[1],z1[0],r1)
        li.append(utm2lonlat(m23[0],m23[1],z23))
    else:
        li.append(None)
    
    if C12 and C13 and C23:
#        print("三个坐标作的圆都有公共点")
        m=[(m12[0]+m13[0]+m23[0])/3,(m12[1]+m13[1]+m23[1])/3]
        li.append(utm2lonlat(m[0],m[1],z))
        return li
    elif C12 or C13 or C23:
#        print("三个坐标作的圆不全有公共点")
        li.append(None)
        return li
    else:
#        print("三个坐标作的圆都没有公共点")
        li.append(None)
        li.append(None)
        li.append(None)
        li.append(None)
        return li
    
    
    
    
def central_win(win):
    win.resizable(0,0)                      # 不可缩放
    screenwidth = win.winfo_screenwidth()	# 获取屏幕分辨率宽
    screenheight = win.winfo_screenheight()	# 获取屏幕分辨率高
    win.update()	# 更新窗口
    width = win.winfo_width()	# 重新赋值
    height = win.winfo_height()
    size = '+%d+%d' % ((screenwidth - width)/2, (screenheight - height)/2)
    # 重新赋值大小 大小为屏幕大小/2
    win.geometry(size) 	# 以新大小定义窗口  
    
def gui_start():
    root=tk.Tk()
    root.title("WSG84三点定位系统 By 网易独家音乐人Mike Zhou")
    mainfram=tk.Frame(root,width=500, height=920)
    mainfram.grid_propagate(0)
    mainfram.grid()
    central_win(root)  
    
    labelName=tk.Label(root, text='经度（正E负W）', justify=tk.LEFT)
    labelName.place(x=120, y=20, width=180, height=50)
    labelName=tk.Label(root, text='纬度（正N负S）', justify=tk.LEFT)
    labelName.place(x=300, y=20, width=180, height=50)
    
    labelName=tk.Label(root, text='位置1:', justify=tk.LEFT)
    labelName.place(x=20, y=70, width=100, height=50)
    labelName=tk.Label(root, text='距离1:', justify=tk.LEFT)
    labelName.place(x=20, y=120, width=100, height=50)
    labelName=tk.Label(root, text='位置2:', justify=tk.LEFT)
    labelName.place(x=20, y=170, width=100, height=50)
    labelName=tk.Label(root, text='距离2:', justify=tk.LEFT)
    labelName.place(x=20, y=220, width=100, height=50)
    labelName=tk.Label(root, text='位置3:', justify=tk.LEFT)
    labelName.place(x=20, y=270, width=100, height=50)
    labelName=tk.Label(root, text='距离3:', justify=tk.LEFT)
    labelName.place(x=20, y=320, width=100, height=50)

    labelName=tk.Label(root, text='12推测点:', justify=tk.LEFT)
    labelName.place(x=20, y=440, width=100, height=50)
    labelName=tk.Label(root, text='13推测点:', justify=tk.LEFT)
    labelName.place(x=20, y=490, width=100, height=50)
    labelName=tk.Label(root, text='23推测点:', justify=tk.LEFT)
    labelName.place(x=20, y=540, width=100, height=50)
    labelName=tk.Label(root, text='中心推测点:', justify=tk.LEFT)
    labelName.place(x=20, y=590, width=100, height=50)
    
    labelName=tk.Label(root, text='米', justify=tk.LEFT)
    labelName.place(x=300, y=120, width=20, height=50)
    labelName=tk.Label(root, text='米', justify=tk.LEFT)
    labelName.place(x=300, y=220, width=20, height=50)
    labelName=tk.Label(root, text='米', justify=tk.LEFT)
    labelName.place(x=300, y=320, width=20, height=50)
    
    labelName=tk.Label(root, text='两点定位1:', justify=tk.LEFT)
    labelName.place(x=20, y=730, width=100, height=50)
    labelName=tk.Label(root, text='两点定位2:', justify=tk.LEFT)
    labelName.place(x=20, y=780, width=100, height=50)
    
    e1_lon = tk.Entry(mainfram)
    #e1.grid(ipadx=50,row=0,column=1)
    e1_lon.delete(0, tk.END)  # 将输入框里面的内容清空
    e1_lon.insert(0, 114.304569)  
    e1_lon.place(x=120, y=70, width=180, height=50) 
    
    e1_r = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    e1_r.delete(0, tk.END)  # 将输入框里面的内容清空
    e1_r.insert(0, 300000)
    e1_r.place(x=120, y=120, width=180, height=50)    
    
    e2_lon = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    e2_lon.delete(0, tk.END)  # 将输入框里面的内容清空
    e2_lon.insert(0, 115.857972)
    e2_lon.place(x=120, y=170, width=180, height=50) 
    
    e2_r = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    e2_r.delete(0, tk.END)  # 将输入框里面的内容清空
    e2_r.insert(0, 400000)
    e2_r.place(x=120, y=220, width=180, height=50)
    
    e3_lon = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    e3_lon.delete(0, tk.END)  # 将输入框里面的内容清空
    e3_lon.insert(0, 116.378517)
    e3_lon.place(x=120, y=270, width=180, height=50)
    
    e3_r = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    e3_r.delete(0, tk.END)  # 将输入框里面的内容清空
    e3_r.insert(0, 900000)
    e3_r.place(x=120, y=320, width=180, height=50)
    
    e1_lat = tk.Entry(mainfram)
    #e1.grid(ipadx=50,row=0,column=1)
    e1_lat.delete(0, tk.END)  # 将输入框里面的内容清空
    e1_lat.insert(0, 30.593354)  
    e1_lat.place(x=300, y=70, width=180, height=50)
    
    e2_lat = tk.Entry(mainfram)
    #e1.grid(ipadx=50,row=0,column=1)
    e2_lat.delete(0, tk.END)  # 将输入框里面的内容清空
    e2_lat.insert(0, 28.682976)  
    e2_lat.place(x=300, y=170, width=180, height=50)
    
    e3_lat = tk.Entry(mainfram)
    #e1.grid(ipadx=50,row=0,column=1)
    e3_lat.delete(0, tk.END)  # 将输入框里面的内容清空
    e3_lat.insert(0, 39.865246)  
    e3_lat.place(x=300, y=270, width=180, height=50)
    
    ex1 = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    ex1.delete(0, tk.END)  # 将输入框里面的内容清空
    ex1.insert(0, "")
    ex1.place(x=120, y=440, width=360, height=50)
    ex1.config(state='readonly')
    
    ex2 = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    ex2.delete(0, tk.END)  # 将输入框里面的内容清空
    ex2.insert(0, "")
    ex2.place(x=120, y=490, width=360, height=50)
    ex2.config(state='readonly')
    
    ex3 = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    ex3.delete(0, tk.END)  # 将输入框里面的内容清空
    ex3.insert(0, "")
    ex3.place(x=120, y=540, width=360, height=50)
    ex3.config(state='readonly')
    
    ex4 = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    ex4.delete(0, tk.END)  # 将输入框里面的内容清空
    ex4.insert(0, "")
    ex4.place(x=120, y=590, width=360, height=50)
    ex4.config(state='readonly')
    
    ey1 = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    ey1.delete(0, tk.END)  # 将输入框里面的内容清空
    ey1.insert(0, "")
    ey1.place(x=120, y=730, width=360, height=50)
    ey1.config(state='readonly')
    
    ey2 = tk.Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    ey2.delete(0, tk.END)  # 将输入框里面的内容清空
    ey2.insert(0, "")
    ey2.place(x=120, y=780, width=360, height=50)
    ey2.config(state='readonly')
    
    def input_judg(e):
        try:
            s=float(str(e.get()))
        except:            
            e.delete(0, tk.END)
            e.insert(0, 0)
            s=0.0
            return s

        if e==e1_lat or e==e2_lat or e==e3_lat:
            if s<-90 or s>90:
                e.delete(0, tk.END)
                e.insert(0, 0)
                s=0.0
        elif e==e1_lon or e==e2_lon or e==e3_lon:
            if s<-180 or s>180:
                e.delete(0, tk.END)
                e.insert(0, 0)
                s=0.0
        elif e==e1_r or e==e2_r or e==e3_r:
            if s<0 or s>400750170:
                e.delete(0, tk.END)
                e.insert(0, 0)
                s=0.0
                
        return s
    
    def view(e,s):
        s=str(s)
        e.config(state='normal')
        e.delete(0, tk.END)
        e.insert(0, s)
        e.config(state='readonly')
        
    def event():
        lat1 = input_judg(e1_lat)
        lon1 = input_judg(e1_lon)
        r1 = input_judg(e1_r)
        
        lat2 = input_judg(e2_lat)
        lon2 = input_judg(e2_lon)
        r2 = input_judg(e2_r)
        
        lat3 = input_judg(e3_lat)
        lon3 = input_judg(e3_lon)
        r3 = input_judg(e3_r)
        
        result = location_judg([lon1,lat1],r1,[lon2,lat2],r2,[lon3,lat3],r3)
        
        view(ex1,result[0])
        view(ex2,result[1])
        view(ex3,result[2])
        view(ex4,result[3])
    
    def double(n):
        lat1 = input_judg(e1_lat)
        lon1 = input_judg(e1_lon)
        r1 = input_judg(e1_r)
        
        lat2 = input_judg(e2_lat)
        lon2 = input_judg(e2_lon)
        r2 = input_judg(e2_r)
        
        lat3 = input_judg(e3_lat)
        lon3 = input_judg(e3_lon)
        r3 = input_judg(e3_r)
        
        if n==1:
            result = location_trans([lon1,lat1],r1,[lon2,lat2],r2)
        elif n==2:
            result = location_trans([lon1,lat1],r1,[lon3,lat3],r3)
        elif n==3:
            result = location_trans([lon2,lat2],r2,[lon3,lat3],r3)
        else:
            result = location_trans([lon1,lat1],r1,[lon2,lat2],r2)
        
        view(ey1,result[0])
        view(ey2,result[1])
        
    def clean():
        view(ex1,"")
        view(ex2,"")
        view(ex3,"")
        view(ex4,"")
        view(ey1,"")
        view(ey2,"")
        
        e1_lon.delete(0, tk.END)
        e1_lon.insert(0, "")
        e2_lon.delete(0, tk.END)
        e2_lon.insert(0, "")
        e3_lon.delete(0, tk.END)
        e3_lon.insert(0, "")
        
        e1_lat.delete(0, tk.END)
        e1_lat.insert(0, "")
        e2_lat.delete(0, tk.END)
        e2_lat.insert(0, "")
        e3_lat.delete(0, tk.END)
        e3_lat.insert(0, "")
        
        e1_r.delete(0, tk.END)
        e1_r.insert(0, "")
        e2_r.delete(0, tk.END)
        e2_r.insert(0, "")
        e3_r.delete(0, tk.END)
        e3_r.insert(0, "")
        
    def start_event():
        t=Thread(target=event)
        t.setDaemon(False)
        t.start()
    
    def start_clean():
        t=Thread(target=clean)
        t.setDaemon(False)
        t.start()
    
    def start_double(i):
        t=Thread(target=double,args=(i,))
        t.setDaemon(False)
        t.start()
        
    def button_event(s):
        if(s.keysym=='C' or s.keysym=='c'):
            start_event()
        elif(s.keysym=='D' or s.keysym=='d'):
            start_clean()
    
    b1=tk.Button(mainfram,width=30,text="计算123三点定位",command=start_event)
    b1.bind_all('C',button_event)
    b1.bind_all('c',button_event)
    b1.place(x=20, y=640, width=460, height=70)
    
    b2=tk.Button(mainfram,width=30,text="清空",command=start_clean)
    b2.bind_all('D',button_event)
    b2.bind_all('d',button_event)
    b2.place(x=20, y=370, width=460, height=50)
    
    b3=tk.Button(mainfram,width=30,text="计算12两点定位",command=lambda:start_double(1))
    b3.place(x=20, y=830, width=140, height=70)
    
    b4=tk.Button(mainfram,width=30,text="计算13两点定位",command=lambda:start_double(2))
    b4.place(x=180, y=830, width=140, height=70)
    
    b5=tk.Button(mainfram,width=30,text="计算23两点定位",command=lambda:start_double(3))
    b5.place(x=340, y=830, width=140, height=70)
    
    start_event()
    start_double(1)
    root.mainloop()
    
if __name__ == "__main__":
    gui_start()
    


